<?php


namespace app\api\controller\xiluedu;


use addons\xiluedu\controller\WeixinMini;
use app\common\controller\Api;
use app\common\model\xiluedu\Course AS CourseModel;
use app\common\model\xiluedu\CourseCode;
use app\common\model\xiluedu\CourseFile;
use app\common\model\xiluedu\UserCollection;
use app\common\model\xiluedu\FooterView;
use app\common\model\xiluedu\UserCourse;
use app\common\model\xiluedu\UserFavourite;
use app\common\model\xiluedu\UserStudy;
use app\common\model\xiluedu\UserVip;
use fast\Date;
use PHPQRCode\QRcode;
use think\Exception;
use function fast\array_get;

class Course extends Api
{
    protected $noNeedLogin = ['video_audio_times','lists','detail','guess_like'];
    protected $noNeedRight = ['*'];


    /**
     * @ApiTitile (视频榜，音频榜)
     * @ApiSummary (视频榜，音频榜)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiluedu.course/guess_like)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=course_id, type=int, require=false, description="课程id")
     */
    public function video_audio_times(){
        $params = $this->request->param('pagesize');
        $pagesize = array_get($params,'pagesize',10);
        $lists = CourseModel::videoAudioSortLists($pagesize);
        $this->success('查询成功', $lists);
    }

    /**
     * 课程列表
     */
    public function lists(){
        $params = $this->request->param('');
        $list = CourseModel::searchLists($params);
        $this->success('查询成功',$list);
    }

    /**
     * 兑换码查询课程
     */
    public function code_course(){
        $params = $this->request->param('');
        $course_code = array_get($params,'course_code');
        if(!$course_code){
            $this->error("非法参数");
        }
        $list = CourseCode::codeCourse($course_code);
        $this->success('查询成功',$list);
    }

    /**
     * 课程兑换
     */
    public function exchange_course(){
        $params = $this->request->param('');
        $course_code = array_get($params,'course_code');
        $course_code_id = array_get($params,'course_code_id');
        if(!$course_code || !$course_code_id){
            $this->error("非法参数");
        }
        try {
            $ret = CourseCode::exchangeCourse($course_code,$course_code_id,$this->auth->id);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('查询成功',$ret);
    }

    /**
     * 课程详情
     */
    public function detail(){
        $params = $this->request->param('');
        $course_id = array_get($params,'course_id');
        if(!$course_id){
            $this->error('非法参数');
        }
        #课程详情
        $row = CourseModel::with([
            'teacher'=>function($query){$query->withField(['id','name','thumb_image','job']);},
            'courseFile'=>function($query){$query->where('status','1')->order('weigh','asc')->field(['id','name','course_id','type','poster_image','is_free','file','file_time']);}
        ])
            ->field('id,type,name,category_id,tag_ids,teacher_id,thumb_image,content,description,introduce,salesprice,market_price,status,poster_image,fav_count,avg_score,is_charge,(basic_num+real_num) total_num,fav_count,collection_count,comment_count,updatetime,play_count')
            ->where('id',$course_id)
            ->find();
        if(!$row){
            $this->error('课程不存在');
        }
        #学习感悟
        $row->course_comment = \app\common\model\xiluedu\CourseComment::lists($row->id,3)->items();

        #收藏判断
        $row->collection_status = $this->auth->isLogin() ? UserCollection::isFav($this->auth->id,$course_id,UserCollection::TYPE_COURSE) : 0;

        #点赞判断
        $row->is_fav_count = $this->auth->isLogin() ? UserFavourite::isFav($this->auth->id,$course_id,UserFavourite::TYPE_COURSE) : 0;

        #是否会员
        $row->is_vip = $row->is_charge != 0 && $this->auth->isLogin() ? UserVip::isVip($this->auth->id) : 0;

        #是否购买
        $row->is_buy = $row->is_charge != 0 && $this->auth->isLogin() ? UserCourse::isBuy($this->auth->id,$row->id) : 0;
        #h5分享链接
        //$share_url = request()->domain()

        #是否免费课程进行中
        $row->is_free = $row->is_charge != 0 ? \app\common\model\xiluedu\CourseFree::isFree($course_id) : 0;

        if($row->type == '3' && (($row->is_charge == 1 && !$row->is_vip && !$row->is_buy) || ($row->is_charge==2 && !$row->is_buy)) && !$row->is_free){
            $row->content = mb_substr( $row->content,0,200);
        }

        $platform = $this->request->param('platform','wxmini');
        $root = '.';
        $filename = md5(mt_rand()).'.png';
        if(!get_addon_config('alioss')){
            $path = "/uploads/".date('Ymd').'/';
        }else{
            $path = "/xiluedu/".date('Ymd').'/';
        }
        if (!file_exists($root . $path)) {
            @mkdir($root . $path, 0777, true);
        }
        $qrcode = $path.$filename;
        if($platform == 'h5'){
            QRcode::png(request()->domain().'/h5/#/pages/course_video_detail/course_video_detail?course_id='.$row->id.'&user_id='.$this->auth->id, $root.$qrcode, 'L', 6, 2);
            $row->qrcode = request()->domain().$qrcode;
        }else{
            $wxmini = new WeixinMini();
            $res = $wxmini->getUnlimited('user_id='.$this->auth->id,'pages/index/index');
            if($res){
                if(!get_addon_config('alioss')){
                    file_put_contents($root.$qrcode,$res);
                }else{
                    Common::uploadAlioss($qrcode, $res);
                }
                $row->qrcode = cdnurl($qrcode,true);
            }
        }

        #足迹
        if($this->auth->isLogin()){
            try {
                FooterView::viewFooter($this->auth->id,$course_id,FooterView::TYPE_COURSE);
            }catch (Exception $e){
                //$this->error($e->getMessage());
            }
        }
        $this->success('查询成功', $row);
    }


    /**
     * 音视频长度
     */
    public function play_time(){
        if(request()->isPost()){
            $param = input('',[]);
            if($this->auth->isLogin()){
                $result = UserStudy::setPlayTime($param,$this->auth->id);
            }
            $this->success();
        }
    }


    /**
     * @ApiTitile (猜你喜欢)
     * @ApiSummary (猜你喜欢)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiluedu.course/guess_like)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=course_id, type=int, require=false, description="课程id")
     */
    public function guess_like(){
        $params = $this->request->param('');
        $course_id = array_get($params,'course_id');
        $pagesize = array_get($params,'pagesize',6);
        #course_id存在，则推荐与课程相关的
        $lists = CourseModel::guessLike($course_id,$pagesize);

        $this->success('查询成功', $lists);
    }


    /**
     * @ApiTitile (收藏&取消收藏)
     * @ApiSummary (收藏&取消收藏)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiluedu.course/toggle_collection)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=course_id, type=int, require=true, description="id")
     */
    public function toggle_collection() {
        $course_id = $this->request->post('course_id');
        $result = UserCollection::toggleCollection($this->auth->id, $course_id, UserCollection::TYPE_COURSE);
        $this->success('操作成功',['collection_status'=>$result]);
    }

    /**
     * @ApiTitile (点赞&取消点赞)
     * @ApiSummary (点赞&取消点赞)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiluedu.course/toggle_fav)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=course_id, type=int, require=true, description="id")
     */
    public function toggle_fav() {
        $forum_id = $this->request->post('course_id');
        $result = UserFavourite::toggleFav($this->auth->id, $forum_id, UserFavourite::TYPE_COURSE);
        $this->success('操作成功',['is_fav_count'=>$result?1:0]);
    }

}